package org.springframework.beans.factory.support;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;

/**
 * CGLIB 子类实例化策略
 */
public class CglibSubclassingInstantiationStrategy implements InstantiationStrategy{
    @Override
    public Object instantiate(BeanDefinition beanDefinition) throws BeansException {
        //CGLIB 动态代理 是基于继承的方式 运行时通过ASM框架动态生成目标类的子类作为代理类 而不是通过反射
        Enhancer enhancer = new Enhancer();
        Class beanClass = beanDefinition.getBeanClass();
        try {
            enhancer.setSuperclass(beanClass);
            enhancer.setCallback((MethodInterceptor) (o, method, args, methodProxy) -> methodProxy.invokeSuper(o, args));
            return enhancer.create();
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }
    }
}
